package my.view;

import my.mvc.RequestContext;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.VelocityLayoutServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by hackway on 2016/5/17.
 */
public class VelocityServlet extends VelocityLayoutServlet {

    private final static Logger log = LoggerFactory.getLogger(VelocityServlet.class);


    @Override
    public void init(ServletConfig config) throws ServletException {
        log.info("init velocity servlet!!!");
        super.init(config);
    }

    @Override
    protected void setContentType(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
    }

    @Override
    protected void error(HttpServletRequest request, HttpServletResponse response, Throwable e) {
        try {
            if (e instanceof ResourceNotFoundException) {
                if (!response.isCommitted()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
            } else {
                StringBuilder logBuf = new StringBuilder("ERROR：Unknown Velocity Error，url=");
                logBuf.append(request.getRequestURL());
                if (request.getQueryString() != null) {
                    logBuf.append("?").append(request.getQueryString());
                }
                logBuf.append('(').append(new Date()).append(')');
                log.error(logBuf.toString(),e);
                request.setAttribute("javax.servlet.jsp.jspException", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
        return super.handleRequest(request, response, ctx);
    }

    @Override
    protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        long runtime = System.currentTimeMillis();
        super.doRequest(request, response);
        if (request.getAttribute("close_comment")==null) {
            RequestContext ctx = RequestContext.get();
            Date cur_time = Calendar.getInstance(request.getLocale()).getTime();
            PrintWriter printWriter = response.getWriter();
            printWriter.printf("\r\n<!-- Generated by hackway.site (init:%s[ms],page:%s[ms],ip:%s) -->",
                    runtime - ctx.getBeginTime(),
                    cur_time.getTime() - runtime,
                    ctx.ip());
        }
    }
}
